package com.cfs.config;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cfs.custom.RedisRepo;

/**
 * Created by Administrator on 2017/9/27/027.
 */
@Component
public class SessionDAO extends AbstractSessionDAO {

    @Autowired
    private RedisRepo redisRepo;

    private static String SESSION_KEY = "web-session:%s";


    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        redisRepo.setSessionEx(String.format(SESSION_KEY,sessionId),session,1, TimeUnit.HOURS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = (Session) redisRepo.getSession(String.format(SESSION_KEY, sessionId));
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        redisRepo.setSessionEx(String.format(SESSION_KEY, session.getId()),session,1, TimeUnit.HOURS);
    }

    @Override
    public void delete(Session session) {
        redisRepo.delete(String.format(SESSION_KEY,session.getId()));
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return Collections.emptySet();
    }
}
